package p.ithorns.sample.module;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import p.ithorns.sample.ModulePath;

import java.util.Set;

/**
 * ServletConfigScanner
 *
 * @author Ht.L
 * @date 2024-07-19 21:34
 * @since 1.0.0
 */
public class ModuleAnnotationScanner extends ClassPathBeanDefinitionScanner {

    private final static Logger log = LoggerFactory.getLogger(ModuleAnnotationScanner.class);


    final BeanDefinitionRegistry registry;

    public ModuleAnnotationScanner(BeanDefinitionRegistry registry) {
        super(registry);
        this.registry = registry;

        // 设置为 false 以避免扫描枚举和接口等
        resetFilters(false);

        // 添加类型过滤，只扫描实现了 MyConfig 接口的类
        addIncludeFilter(new AnnotationTypeFilter(ModulePath.class));
    }


    public Set<BeanDefinition> scan(String packageName) {
        // 扫描整个类路径
        return findCandidateComponents(packageName);
    }


    @Override
    public boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        AnnotationMetadata metadata = beanDefinition.getMetadata();
        return metadata.isIndependent() && !metadata.isAnnotation() && (metadata.isAbstract() || metadata.isInterface());
    }
}